var requester = require('../../common/requester.js');
var config = require('../../common/config.js');
var user = require('../../common/user.js');

Page({
    data: {
        newAvatar: ''
    },

    onLoad: function () {
        const info = wx.getStorageSync(config.storage.keyUserInfo);
        this.setData({
            info: info,
            nickName: info.nickName,
            introduction: info.introduction
        })
    },
    selectAvatar: function () {
        let me = this;
        wx.chooseImage({
            count: 1, // 默认9
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                let tempFilePath = res.tempFilePaths[0];
                me.setData({
                    avatarUrl: tempFilePath
                })
            }
        })
    },
    modifyNickName(e) {
        let val = e.detail.value;
        this.setData({
            nickName: val
        })
    },
    modifyIntroduction(e) {
        let val = e.detail.value;
        this.setData({
            introduction: val
        })
    },
    upload() {
        wx.showToast({
            title: '正在上传',
            icon: 'loading',
            duration: 10000
        });
        let p1 = this.avatarUpload();
        let p2 = this.textUpload();
        Promise.all([p1, p2])
            .then(() => {
                wx.showToast({
                    title: '修改成功'
                });
                user.getThirdUserInfo();
                wx.navigateBack();
            })
    },
    avatarUpload() {
        let path = this.data.avatarUrl;
        let reqObj = {
            url: requester.service.updateAvatar,
            filePath: path,
            name: 'avatarPicFile',
            formData: {},
        };
        if (!path) {
            return Promise.resolve();
        }
        return requester.uploadFile(reqObj)
            .then(res => res.data)
    },
    textUpload() {
        const {introduction, nickName} = this.data;
        let data = {
            nickName: nickName,
            introduction: introduction
        };
        if ((nickName === this.data.info.nickName) && (introduction === this.data.info.introduction)) {
            return Promise.resolve();
        }
        return requester.request({
            url: requester.service.updateUser,
            method: 'POST',
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: data
        });
    }
});